package com.example.demo.util;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.example.demo.exception.TokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JwtUtil {
    /**
     * 生成token
     *
     * @param userId 生成参数
     * @return
     */
    public static String generateToken(Long userId) {
        String token = JWT.create()
                .setPayload("userId", userId)
                .setSigner(JWTSignerUtil.none())
                .sign();
        log.info("[用户token生成成功:{}]", token);
        return token;
    }

    /**
     * 验证token
     *
     * @param token token值
     * @return
     */
    public static boolean verifyToken(String token) throws TokenException {
        boolean verify = JWT.of(token).setSigner(JWTSignerUtil.none()).verify();
        log.info("[用户token验证结果:{}]", verify);
        return verify;
    }

    /**
     * 解析token
     * @param token token值
     * @param key  键名
     * @return
     */
    public static Object getPayload(String token, String key){
        Object payload = JWT.of(token).setSigner(JWTSignerUtil.none()).getPayload(key);
        log.info("[用户token获取payload:{}]",payload);
        return payload;
    }

}
